import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { Tag } from './entities/tag.entity';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { TagQueryDto } from './dto/tag-query.dto';

@Injectable()
export class TagsService {
  constructor(
    @InjectRepository(Tag)
    private readonly tagRepository: Repository<Tag>,
  ) {}

  async findAll(query: TagQueryDto, userId: number) {
    const { keyword, page = 1, pageSize = 20 } = query;
    const skip = (page - 1) * pageSize;

    const where: any = { userId };
    if (keyword) {
      where.name = Like(`%${keyword}%`);
    }

    const [list, total] = await this.tagRepository.findAndCount({
      where,
      skip,
      take: pageSize,
      order: { createdAt: 'DESC' },
    });

    const totalPages = Math.ceil(total / pageSize);

    return {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages,
        hasMore: page < totalPages,
      },
    };
  }

  async findOne(id: number, userId: number) {
    const tag = await this.tagRepository.findOne({
      where: { id, userId },
      relations: ['textTags', 'textTags.text'],
    });

    if (!tag) {
      throw new NotFoundException('标签不存在');
    }

    return tag;
  }

  async create(createTagDto: CreateTagDto, userId: number) {
    const existingTag = await this.tagRepository.findOne({
      where: { name: createTagDto.name, userId },
    });

    if (existingTag) {
      throw new ConflictException('标签名称已存在');
    }

    const tag = this.tagRepository.create({
      ...createTagDto,
      userId,
      color: createTagDto.color || '#3498db',
    });

    return await this.tagRepository.save(tag);
  }

  async update(id: number, updateTagDto: UpdateTagDto, userId: number) {
    const tag = await this.tagRepository.findOne({ where: { id, userId } });

    if (!tag) {
      throw new NotFoundException('标签不存在');
    }

    if (updateTagDto.name && updateTagDto.name !== tag.name) {
      const existingTag = await this.tagRepository.findOne({
        where: { name: updateTagDto.name, userId },
      });

      if (existingTag) {
        throw new ConflictException('标签名称已存在');
      }
    }

    await this.tagRepository.update(id, updateTagDto);
    return await this.tagRepository.findOne({ where: { id } });
  }

  async remove(id: number, userId: number) {
    const tag = await this.tagRepository.findOne({ where: { id, userId } });

    if (!tag) {
      throw new NotFoundException('标签不存在');
    }

    await this.tagRepository.remove(tag);
  }
}